import _classCallCheck from "@babel/runtime/helpers/esm/classCallCheck";
import _createClass from "@babel/runtime/helpers/esm/createClass";
import _applyDecoratedDescriptor from "@babel/runtime/helpers/esm/applyDecoratedDescriptor";
import _isString from "lodash/isString";
import _isFunction from "lodash/isFunction";

var _dec, _dec2, _dec3, _dec4, _dec5, _dec6, _dec7, _dec8, _dec9, _class;

import { Bind } from 'lodash-decorators';
import EventEmitter from 'event-emitter';
import SockJs from 'sockjs-client';
import { getEnvConfig } from "./iocUtils";
import { getAccessToken } from "./utils";

var _getEnvConfig = getEnvConfig(),
    WEBSOCKET_URL = _getEnvConfig.WEBSOCKET_URL;
/**
 * 标志这 socket 的状态
 * unInit:  没有初始化
 * error:   出现错误(建立连接)
 * init:    初始化成功
 * close:   关闭
 * @type {{init: number, error: number, close: number, unInit: number}}
 */


var SocketStatus = {
  unInit: 0,
  error: 2,
  close: 4,
  init: 32,
  count: 5
};
var WebSocketManagener = (_dec = Bind(), _dec2 = Bind(), _dec3 = Bind(), _dec4 = Bind(), _dec5 = Bind(), _dec6 = Bind(), _dec7 = Bind(), _dec8 = Bind(), _dec9 = Bind(), (_class = /*#__PURE__*/function () {
  function WebSocketManagener() {
    _classCallCheck(this, WebSocketManagener);

    this.eventManagener = new EventEmitter();
    this.socketStatus = SocketStatus.unInit;
    this.count = 0;
    this.heartbeatPackageTimer = void 0;
  }

  _createClass(WebSocketManagener, [{
    key: "componentWillUnmount",
    value: function componentWillUnmount() {
      if (this.heartbeatPackageTimer !== undefined) {
        clearInterval(this.heartbeatPackageTimer);
        this.heartbeatPackageTimer = undefined;
      }
    }
    /**
     * 发送心跳包
     */

  }, {
    key: "intervalHeartbeatPackage",
    value: function intervalHeartbeatPackage() {
      if (this.socket.readyState !== 1) {
        if (this.count > SocketStatus.count) {
          this.destroyWebSocket();
        } else {
          this.initWebSocket();
        }
      } else {
        this.socket.send('cpaas-hi');
      }
    }
  }, {
    key: "handleSocketOpen",
    value: function handleSocketOpen() {
      this.socketStatus = SocketStatus.init;
      this.heartbeatPackageTimer = setInterval(this.intervalHeartbeatPackage, 45000);
      this.count = 0;
    }
    /**
     * 当webSocket返回信息时执行
     * @param {Object} message 返回对象
     */

  }, {
    key: "handleSocketMessage",
    value: function handleSocketMessage(message) {
      var res = JSON.parse(message.data || {});

      if (res) {
        this.eventManagener.emit("".concat(res.key), res);
      }
    }
    /**
     * 关闭webSocket连接
     */

  }, {
    key: "destroyWebSocket",
    value: function destroyWebSocket() {
      if (this.socketStatus === SocketStatus.init) {
        this.socket.close();
      }

      this.socketStatus = SocketStatus.close;

      if (this.heartbeatPackageTimer !== undefined) {
        clearInterval(this.heartbeatPackageTimer);
        this.heartbeatPackageTimer = undefined;
      }
    }
    /**
     * 监听到 websocket 关闭连接
     */

  }, {
    key: "handleSocketClose",
    value: function handleSocketClose() {
      this.socketStatus = SocketStatus.close; // if (this.heartbeatPackageTimer !== undefined) {
      //   clearInterval(this.heartbeatPackageTimer);
      //   this.heartbeatPackageTimer = undefined;
      // }

      if (!this.heartbeatPackageTimer) {
        this.heartbeatPackageTimer = setInterval(this.intervalHeartbeatPackage, 45000);
      }

      this.count += 1;
    }
    /**
     * 增加监听事件
     */

  }, {
    key: "addListener",
    value: function addListener(type, handler) {
      if (_isString(type) && _isFunction(handler)) {
        this.eventManagener.on(type, handler);
      }
    }
    /**
     * 移除监听事件
     */

  }, {
    key: "removeListener",
    value: function removeListener(type, handler) {
      if (_isString(type) && _isFunction(handler)) {
        this.eventManagener.off(type, handler);
      }
    }
    /**
     * 移除所有监听事件
     */

  }, {
    key: "removeAllListeners",
    value: function removeAllListeners(type) {
      if (_isString(type)) {
        this.eventManagener.off(type);
      }
    }
    /**
     * 建立 webSocket 连接
     */

  }, {
    key: "initWebSocket",
    value: function initWebSocket() {
      var accessToken = getAccessToken();

      if (WEBSOCKET_URL === 'BUILD_WEBSOCKET_URL' || !WEBSOCKET_URL) {
        this.socketStatus = SocketStatus.unInit; // console.error('websocket 未配置');

        this.socket = {
          close: function close() {}
        };
      } else {
        try {
          if (WEBSOCKET_URL.startsWith('ws')) {
            this.socket = new WebSocket("".concat(WEBSOCKET_URL, "?access_token=").concat(accessToken));
          } else if (WEBSOCKET_URL.startsWith('http')) {
            this.socket = new SockJs("".concat(WEBSOCKET_URL, "?access_token=").concat(accessToken));
          } else if (WEBSOCKET_URL.startsWith('/api')) {
            this.socket = new SockJs("".concat(WEBSOCKET_URL, "?access_token=").concat(accessToken));
          }

          if (this.socket) {
            this.socket.onopen = this.handleSocketOpen;
            this.socket.onmessage = this.handleSocketMessage;
            this.socket.onclose = this.handleSocketClose;
          }
        } catch (err) {
          // 不在页面显示websocket连接失败
          // console.error(
          //   intl.get('cpaas.common.notification.error.webSocket').d('webSocket连接失败!')
          // );
          this.socketStatus = SocketStatus.error;
          this.socket = {
            close: function close() {}
          };
        }
      }
    }
  }, {
    key: "sendMessage",
    value: function sendMessage(service, key, data) {
      if (this.socketStatus === SocketStatus.init) {
        this.socket.send(JSON.stringify({
          service: service,
          key: key,
          message: JSON.stringify(data)
        }));
      }
    }
  }]);

  return WebSocketManagener;
}(), (_applyDecoratedDescriptor(_class.prototype, "intervalHeartbeatPackage", [_dec], Object.getOwnPropertyDescriptor(_class.prototype, "intervalHeartbeatPackage"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "handleSocketOpen", [_dec2], Object.getOwnPropertyDescriptor(_class.prototype, "handleSocketOpen"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "handleSocketMessage", [_dec3], Object.getOwnPropertyDescriptor(_class.prototype, "handleSocketMessage"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "destroyWebSocket", [_dec4], Object.getOwnPropertyDescriptor(_class.prototype, "destroyWebSocket"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "handleSocketClose", [_dec5], Object.getOwnPropertyDescriptor(_class.prototype, "handleSocketClose"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "addListener", [_dec6], Object.getOwnPropertyDescriptor(_class.prototype, "addListener"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "removeListener", [_dec7], Object.getOwnPropertyDescriptor(_class.prototype, "removeListener"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "removeAllListeners", [_dec8], Object.getOwnPropertyDescriptor(_class.prototype, "removeAllListeners"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "sendMessage", [_dec9], Object.getOwnPropertyDescriptor(_class.prototype, "sendMessage"), _class.prototype)), _class));
var webSocketManagener = new WebSocketManagener();
export default webSocketManagener;